// pages/new-pages/main-page/main-page.js
const app = getApp();
import Toast from '../../../component/toast/toast';
import {formatTime} from '../../../utils/util.js'
let cerealsToast;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        position: 2,
        // 企业参数
        componyName: '',
        componyTrade: '',
        scale: '',
        finance: '',
        enterpriseLogo: '',
        teamDes: '',
        address: '',
        isVideo: false,
        mediaCoverUrl: '',
        codeStatu: '获取验证码',
        showUnbind: false,
        isCountDown: false,
        phoneCode: '',
        phoneNumber: '',
        // 企业参数

        // 个人简历参数
        resumeData: null,
        jobWayObj: null,
        isOpen: 0,
        // 个人简历参数
        authChecked: false,
        verifyStatus: 1,
        isShowGuide:false,
        showShare:false
    },
    clickItem: function(event) {
        let index = event.target.id;
        this.setData({
            position: index
        });
        if (index == 1 && !this.data.componyTrade) {
            this.getEnterpriseInfoById();
        } else if (index == 2 && !this.data.resumeData) {
            this.getResumeInfoById();
        }
    },
    //企业解绑
    clickUnbind() {
        this.setData({
            showUnbind: true
        });
    },
    //点击空白处关闭解绑弹框
    clickUnbindFull() {
        this.setData({
            showUnbind: false
        });
    },
    bindSmsCodeClick() {
        // console.log("进入");
        if (this.data.isCountDown) {
            return;
        }
        this.sendRegisterSMS(this.data.phoneNumber);
    },
    phoneCode(e) {
        this.setData({
            phoneCode: e.detail.value
        });
    },
    //确认解绑
    confirmUnbind() {
        if (!this.data.phoneCode || this.data.phoneCode.length < 6) {
            Toast("请填写6位数验证码！");
            return;
        }
        this.unbindEnterprise();
    },
    unbindEnterprise() {
        let data = {};
        data.CurrentUserInfoId = app.userInfo.Id;
        data.EnterpriseInfoId = app.globalData.enterpriseInfo.Id;
        data.MobileNumber = this.data.phoneNumber;
        data.Code = this.data.phoneCode;
        console.log("解绑的数据:", data);
        let that = this;
        wx.showLoading({
            title: '加载中...',
            mask: true
        });
        wx.request({
            url: app.globalData.serverAddress.unbindEnterprise,
            method: 'POST',
            data: data,
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            success: function (res) {
                console.log(res);
                if (res.statusCode == 200) {
                    if (res.data.CodeStatus == 20000) {
                        setTimeout(function(){
                            wx.navigateBack({
                                delta: 1
                            });
                        } ,500)
                    }
                } else {
                    console.error("unbindEnterprise:" + JSON.stringify(res));
                }
                Toast(res.data.Message);
            },
            fail: function (res) {
                console.log("unbindEnterprise:" + JSON.stringify(res));
            },
            complete: function (res) {
                wx.hideLoading();
            }
        });
    },
    countDown() {
        let countDown = 60;
        let timer;
        let that = this;
        timer = setInterval(function() {
            if (countDown == 0) {
                that.setData({
                    codeStatu: '获取验证码',
                    isCountDown: false
                });
                clearTimeout(timer);
            } else {
                --countDown;
                that.setData({
                    codeStatu: countDown + 's',
                    isCountDown: true
                });
            }
        }, 1000);
    },
    /**
     * ===================事件处理部分===================
     */
    // 扫码上传
    clickScanner(){
        let that = this;
        wx.navigateTo({
            url: '/pages/new-pages/scan-hint/scan-hint?resumeId=' + that.data.resumeData.Id
        })
        // try {
            // const value = wx.getStorageSync('no_hint_scan')
            // if (value) {
            //     wx.scanCode({
            //         success(res) {
            //             let result = res.result.substr(4);
            //             console.log(result)
            //             wx.showLoading({
            //                 title: '加载中...',
            //                 mask: true
            //             })
            //             wx.request({
            //                 url: app.globalData.serverAddress.updateLoginQRCode,
            //                 data: {
            //                     Id: result,
            //                     UserInfoId:app.userInfo.Id,
            //                     ExtField: that.data.resumeData.Id
            //                 },
            //                 header: {
            //                     'Authorization': "Bearer " + app.globalData.token
            //                 },
            //                 method: 'POST',
            //                 success: function (res) {
            //                     console.log('updateLoginQRCode response', res);
            //                     if (res.statusCode == 200) {
            //                         if (res.data.CodeStatus == 20000) {
                                     
            //                         }
            //                     }
            //                     Toast(res.data.Message);
            //                 },
            //                 fail: function (res) {
            //                     console.log("updateLoginQRCode fail", res)
            //                     Toast('扫码失败，请重新扫码')
            //                 },
            //                 complete: function (res) {
            //                     wx.hideLoading();
            //                 },
            //             })
            //         }
            //     })
            // }else{
        //         wx.navigateTo({
        //             url: '/pages/new-pages/scan-hint/scan-hint?resumeId='+that.data.resumeData.Id
        //         })
        //     // }
        // } catch (e) {
        //     // Do something when catch error
        // }

    },
    // 点击查看头像
    clickProfile() {
        if (this.data.resumeData.Profile) {
            wx.previewImage({
                current: this.data.resumeData.Profile,
                urls: [this.data.resumeData.Profile]
            })
        }
    },
    // 查看附件
    clickLook(){
        let fileUrl = this.data.resumeData.FileUrl;
        let fileType = this.data.resumeData.FileExtension
        if(!fileUrl){
            Toast('请先扫码上传简历附件')
            return;
        }
        if(fileType == 'jpg' || fileType == 'png' || fileType == 'jpeg'){
            wx.previewImage({
                urls: [fileUrl]
            })
            return;
        }
        wx.showLoading({
            title: '加载中...',
            mask: true
        })
        wx.downloadFile({
            url: fileUrl,
            success: function(res) {
                wx.openDocument({
                    filePath: res.tempFilePath,
                    fileType: fileType,
                    fail(res){
                        console.error('openDocument fail:' , res)
                        Toast('打开简历附件失败')
                    }
                })
            },
            fail: function(res) {
                console.error('downloadFile fail：' , res)
                Toast('查看附件失败')
            },
            complete: function(res) {
                wx.hideLoading()
            },
        })
    },
    previewImg() {
        wx.previewImage({
            current: this.data.mediaCoverUrl,
            urls: [this.data.mediaCoverUrl]
        })
    },
    clickAddMedia() {
        if (this.data.verifyStatus != 2) {
            return;
        }
        wx.navigateTo({
            url: '/pages/compony-pages/compony-media-list/compony-media-list'
        })
    },
    clickEdit() {
        if (this.data.verifyStatus != 2) {
            return;
        }
        wx.navigateTo({
            url: '/pages/compony-pages/edit-compony/edit-compony'
        })
    },
    clickAddress() {
        if (this.data.verifyStatus != 2) {
            return;
        }
        wx.navigateTo({
            url: '/pages/compony-pages/compony-address/compony-address'
        })
    },
    //手机号解绑拦截事件
    myCatchTouch(){},
    clickGuide(){
        this.setData({
            isShowGuide:false,
        });

    },
    handleShare(){
        this.setData({
            showShare: false
        });
        this.addShareRecord();
    },
    addShareRecord(){
        let that = this;
        wx.request({
            url: app.globalData.serverAddress.addShareRecord,
            data: {
                UserInfoId: that.data.resumeData.UserInfoId,
                CreateDateTime:formatTime(new Date())
            },
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'POST',
            success: function (res) {
                console.log('addShareRecord response', res);
                if (res.statusCode == 200) {
                    if (res.data.CodeStatus == 20000) {
                        let data = res.data.BodyContent;
                        app.globalData.resumeInfo = data;
                        that.setData({
                            resumeData: data,
                            authChecked: data.IsOpen == 1
                        })
                    } else {
                        Toast(res.data.Message);
                    }
                } 
            },
            fail: function (res) {
                console.log("addShareRecord fail", res)
            },
            complete: function (res) {
                wx.hideLoading();
            },
        })
    },
    /**
     * ===================事件处理部分===================
     */

    /**
     * -------------------网络请求部分-------------------
     */
    sendRegisterSMS(phoneNum) {
        let that = this;
        wx.showLoading({
            title: '加载中...',
            mask: true
        });
        wx.request({
            url: app.globalData.serverAddress.sendRegisterSms,
            method: 'POST',
            data: {
                MobileNumber: phoneNum
            },
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            success: function(res) {
                console.log(res);
                if (res.statusCode == 200) {
                    if (res.data.CodeStatus == 20000) {
                        that.countDown();
                    }
                } else {
                    console.error("getPhoneNumber:" + JSON.stringify(res));
                }
                Toast(res.data.Message);
            },
            fail: function(res) {
                console.log("getPhoneNumber:" + JSON.stringify(res));
            },
            complete: function(res) {
                wx.hideLoading();
            }
        })
    },
    /**
     * -------------------网络请求部分-------------------
     */
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        cerealsToast = this.selectComponent('#cereals-toast')
        this.setData({
            phoneNumber:app.userInfo.MobileNumber
        })
        try {
            var value = wx.getStorageSync('firstRun')
            if (!value) {
                this.setData({
                    isShowGuide:true
                })
                wx.setStorageSync('firstRun', true)
            }
        } catch (e) {
            // Do something when catch error
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },
    getEnterpriseInfoById(func) {
        wx.showLoading({
            title: '加载中...',
            mask: true
        });
        let that = this;
        wx.request({
            url: app.globalData.serverAddress.getEnterpriseInfoById,
            data: {
                userInfoId: app.userInfo.Id
            },
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'GET',
            success: function(res) {
                console.log('getEnterpriseInfoById success', res);
                if (res.statusCode == 200) {
                    if (res.data.CodeStatus == 20000) {
                        let verifyStatus = res.data.BodyContent.VerifyStatus;
                        if (verifyStatus == 2) {
                            app.globalData.enterpriseInfo = res.data.BodyContent;
                            let address = app.globalData.enterpriseInfo.Province + app.globalData.enterpriseInfo.City + app.globalData.enterpriseInfo.District + app.globalData.enterpriseInfo.Address;
                            let mediaCover = app.globalData.enterpriseInfo.ImageCover;
                            let isVideo = false;
                            if (mediaCover && mediaCover.substring(mediaCover.lastIndexOf('.') + 1) == 'mp4') {
                                isVideo = true;
                            }
                            that.setData({
                                componyName: app.globalData.enterpriseInfo.EnterpriseName,
                                componyTrade: app.globalData.enterpriseInfo.IndustryName,
                                finance: app.globalData.enterpriseInfo.FinancingStage,
                                scale: app.globalData.enterpriseInfo.Scale,
                                enterpriseLogo: app.globalData.enterpriseInfo.EnnterpriseLogo,
                                teamDes: app.globalData.enterpriseInfo.TeamDes,
                                address: address,
                                isVideo: isVideo,
                                mediaCoverUrl: mediaCover
                            });
                        }
                        if (func) {
                            func(verifyStatus);
                        }
                    } else {
                        func(0);
                    }
                } else {
                    // Toast("请求")
                }
            },
            fail: function(res) {
                console.log("getEnterpriseInfoById fail", res)
            },
            complete: function(res) {
                wx.hideLoading();
            },
        })
    },

    /**
     * ---------------------------------------个人简历部分---------------------------------------------
     */
    clickRumeEdit() {
        wx.navigateTo({
            url: '/pages/resume-pages/edit-info/edit-info'
        })
    },
    addExpect() {
        let parmas = {};
        if (this.data.resumeData && this.data.resumeData.Skills) {
            parmas.resumeInfoId = this.data.resumeData.Id;
            parmas.jobWayObj = {};
            parmas.jobWayObj.Id = this.data.resumeData.JobPosition;
            parmas.jobType = this.data.resumeData.JobPositionText;
            parmas.salaryValue = this.data.resumeData.HourlySalary;
            // parmas.selectSalary[0] = parmas.selectSalary[0] + "K";
            parmas.monthWorkHours = this.data.resumeData.WorkTime + "h";
            parmas.mode = {};
            parmas.mode.ParamName = this.data.resumeData.JobModeText;
            parmas.mode.Id = this.data.resumeData.JobMode;
            parmas.workHour = {};
            parmas.workHour.ParamName = this.data.resumeData.WorkingHoursText;
            parmas.workHour.Id = this.data.resumeData.WorkingHours;
            parmas.skillNameArr = [];
            let size = this.data.resumeData.Skills.length;
            for (let i = 0; i < size; i++) {
                parmas.skillNameArr.push(this.data.resumeData.Skills[i].SkillName);
            }
            parmas.Skills = this.data.resumeData.Skills;
        }
        console.log("transmit data:", parmas);
        wx.navigateTo({
            url: '/pages/resume-pages/job-expect/job-expect?parmas=' + JSON.stringify(parmas)
        })
    },
    addExperience() {
        wx.navigateTo({
            url: '/pages/resume-pages/job-experience/job-experience'
        })
    },
    getResumeInfoById() {
        wx.showLoading({
            title: '加载中...',
            mask: true
        });
        let that = this;
        wx.request({
            url: app.globalData.serverAddress.getResumeInfoById,
            data: {
                userInfoId: app.userInfo.Id
            },
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'GET',
            success: function(res) {
                console.log('getResumeInfoById response', res);
                if (res.statusCode == 200) {
                    if (res.data.CodeStatus == 20000) {
                        let data = res.data.BodyContent;
                        app.globalData.resumeInfo = data;
                        that.setData({
                            resumeData: data,
                            authChecked: data.IsOpen == 1
                        })
                    }
                } else {
                    Toast(res.data.Message);
                }
            },
            fail: function(res) {
                console.log("getResumeInfoById fail", res)
            },
            complete: function(res) {
                wx.hideLoading();
            },
        })
    },
    clickEditExperience(e) {
        let index = e.currentTarget.dataset.index;
        let obj = this.data.resumeData.WorkExperiences[index];
        wx.navigateTo({
            url: '/pages/resume-pages/job-experience/job-experience?parmas=' + JSON.stringify(obj)
        })
    },
    //教育经历
    clickEducation: function(e) {
        let index = e.currentTarget.id;
        let url = '';
        switch (index) {
            case '1':
                url = '/pages/resume-pages/education-experience/education-experience'
                break;
        }
        wx.navigateTo({
            url: url
        })
    },
    //教育经历编辑
    clickEditEducation(e) {
        let index = e.currentTarget.dataset.index;
        let obj = this.data.resumeData.EducationalExperiences[index];
        wx.navigateTo({
            url: '/pages/resume-pages/education-experience/education-experience?parmas=' + JSON.stringify(obj)
        })
    },
    switchChange(e) {
        console.log(e.detail.value);
        if (!this.data.resumeData) {
            return;
        }
        wx.showLoading({
            title: '加载中...',
            mask: true
        });
        let id = this.data.resumeData.Id;
        let switchResult = e.detail.value;
        let isOpen = switchResult ? 1 : 0;
        let that = this;
        wx.request({
            url: app.globalData.serverAddress.setResumeIsOpen,
            data: {
                Id: id,
                IsOpen: isOpen
            },
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'POST',
            success: function(res) {
                console.log("setResumeIsOpen response", res);
                if (res.statusCode == 200) {
                    if (res.data.CodeStatus == 20000) {
                        isOpen = switchResult;
                    } else {
                        isOpen = !switchResult;
                    }
                    app.globalData.creditType = 1;
                    app.saveCredit(function (count) {
                        cerealsToast.show(count);
                    });
                    Toast(res.data.Message);
                } else {
                    isOpen = !switchResult;
                    Toast("保存失败，请检查网络！");
                }
                let showShare = false;
                // if(that.data.resumeData.IsShare==0 && !isOpen){
                //     showShare = true;
                // }
                that.setData({
                    authChecked: isOpen,
                    showShare: showShare
                })
            },
            fail: function(res) {},
            complete: function(res) {
                wx.hideLoading();
            },
        })
    },
    checkboxChange(e) {
        let authChecked = this.data.authChecked;
        this.setData({
            authChecked: !authChecked
        })
    },
    //分享红包点击空白部分消失
    clickShareFull(){
        this.setData({
            showShare:false
        })
    },
    /**
     * ---------------------------------------个人简历部分---------------------------------------------
     */
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        let that = this;
        this.getResumeInfoById();
        // if (this.data.position == 1) {
        //     this.getEnterpriseInfoById(function(verifyStatus) {
        //         let data = {
        //             position: 1,
        //             verifyStatus: verifyStatus
        //         };
        //         if (verifyStatus != 2) {
        //             data.position = 2;
        //             wx.setNavigationBarTitle({
        //                 title: '我的简历'
        //             })
        //             that.getResumeInfoById();
        //         }
        //         that.setData(data);
        //     });
        // } else {
        //     this.getResumeInfoById();
        // }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    }
})